package com.jph.simple;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.protobuf.InvalidProtocolBufferException;

import adapter.ContentAdapter;
import adapter.FriendAdapter;
import container.ChatManager;
import model.Friend;
import socket.ServerSession;
import utgame.UtMessage;
import utgame.UtMessage.PlayerInfo;
import utgame.UtMessage.MS_RequestFriends;
import utgame.UtMessage.MS_PlayerChat;
import utgame.UtMessage.MS_OfflineChat;
import utgame.UtMessage.OfflineChat;
import utgame.UtMessage.ChatMsg;
import utgame.UtMessage.MS_PlayerOnline;
import utgame.UtMessage.MS_PlayerOffline;
import utgame.UtMessage.MessagePacket.MessageType;


public class FriendActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String TAG = "FriendActivity";

    private List<View> lists = new ArrayList<View>();
    private ContentAdapter mPageAdapter;
    private ViewPager viewPager;

    private LinearLayout mHomeLayout;
    private LinearLayout mSelfLayout;

    private Fragment homeFragment;
    private Fragment selfFragment;

    private int currentItem;

    private ListView lvFriends;
    private List<Friend> friendList = new ArrayList<>();  //创建集合保存水果信息

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MessageType.RequestFriends_VALUE:
                    try {
                        MS_RequestFriends requestFriends = MS_RequestFriends.parseFrom((byte[]) msg.obj);

                        List<PlayerInfo> playerInfoList = requestFriends.getFriendList();
                        for (int i = 0; i < playerInfoList.size(); ++i){
                            friendList.add(new Friend(Friend.imageIds[i % Friend.imageIds.length], playerInfoList.get(i).getName(), playerInfoList.get(i).getIsOnline()));
                        }
                        Collections.sort(friendList, new SortFriendByOnline());

                        // 离线消息
                        MS_OfflineChat msOfflineChat = ChatManager.getInstance().getOfflineChat();
                        if (msOfflineChat != null){
                            List<com.google.protobuf.ByteString> offlineChatList = msOfflineChat.getOfflineChatList();
                            for (com.google.protobuf.ByteString byteString : offlineChatList){
                                OfflineChat offlineChat = OfflineChat.parseFrom(byteString);

                                List<ChatMsg> chatMsgList = offlineChat.getMsgList();
                                if (!chatMsgList.isEmpty()){
                                    for (Friend friend : friendList){
                                        if (friend.getName().equals(chatMsgList.get(0).getSender())){
                                            friend.setNewMessage(true);
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        FriendAdapter fruitAdapter = new FriendAdapter(FriendActivity.this,
                                R.layout.listview_item, friendList);          //关联数据和子布局
                        lvFriends.setAdapter(fruitAdapter);                   //绑定数据和适配器

                        lvFriends.setOnItemClickListener(new OnItemClickListener() {  //点击每一行的点击事件

                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int position,
                                                    long id) {
                                Friend friend= friendList.get(position);         //获取点击的那一行

                                Intent intent = new Intent();
                                Bundle bundle = new Bundle();
                                bundle.putString("name", friend.getName());
                                intent.setClass(FriendActivity.this, PlayerChatActivity.class);
                                intent.putExtras(bundle);

                                startActivity(intent);
                                FriendActivity.this.finish();
                            }
                        });

                        checkNewMessage();

                    } catch (InvalidProtocolBufferException e) {
                        e.printStackTrace();
                    }
                    break;
                case MessageType.PlayerChat_VALUE:
                    if (!isTopActivity()) return;

                    try {
                        MS_PlayerChat chat = MS_PlayerChat.parseFrom((byte[])msg.obj);
                        ChatManager.getInstance().addChat(chat.getSenderName(), chat.getChatContent());

                        checkNewMessage();
                    } catch (InvalidProtocolBufferException e) {
                        e.printStackTrace();
                    }
                    break;
                case MessageType.PlayerOnline_VALUE:

                    if (!isTopActivity()) return;

                    try {
                        MS_PlayerOnline msPlayerOnline = MS_PlayerOnline.parseFrom((byte[])msg.obj);
                        updateOnline(msPlayerOnline.getName(), true);

                    } catch (InvalidProtocolBufferException e) {
                        e.printStackTrace();
                    }

                    break;
                case MessageType.PlayerOffline_VALUE:

                    if (!isTopActivity()) return;

                    try {
                        MS_PlayerOffline msPlayerOffline = MS_PlayerOffline.parseFrom((byte[])msg.obj);
                        updateOnline(msPlayerOffline.getName(), false);

                    } catch (InvalidProtocolBufferException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend);
        lvFriends = (ListView) findViewById(R.id.lvFriends);   //获得子布局

        mHomeLayout = (LinearLayout) findViewById(R.id.ll_home);
        mSelfLayout = (LinearLayout) findViewById(R.id.ll_self);

        mHomeLayout.setOnClickListener(this);
        mSelfLayout.setOnClickListener(this);
//        getData();
//        FriendAdapter fruitAdapter = new FriendAdapter(this,
//                R.layout.listview_item, friendList);          //关联数据和子布局
//        lvFriends.setAdapter(fruitAdapter);                   //绑定数据和适配器
//
//        lvFriends.setOnItemClickListener(new OnItemClickListener() {  //点击每一行的点击事件
//
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int position,
//                                    long id) {
//                Friend friend= friendList.get(position);         //获取点击的那一行
//                Toast.makeText(FriendActivity.this, friend.getName(), Toast.LENGTH_SHORT).show();//使用吐司输出点击那行水果的名字
//            }
//        });
        ServerSession.getInstance().addHandler(TAG, mHandler);

        lists.add(getLayoutInflater().inflate(R.layout.layout_friendlist, null));
//        lists.add(getLayoutInflater().inflate(R.layout.layout2, null));
//        lists.add(getLayoutInflater().inflate(R.layout.layout3, null));

        mPageAdapter = new ContentAdapter(lists);

        viewPager = (ViewPager) findViewById (R.id.vp_content);
        viewPager.setAdapter(mPageAdapter);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {                                 //当滑动式，顶部的imageView是通过animation缓慢的滑动
                // TODO Auto-generated method stub
                switch (arg0)
                {
                    case 0:
                }
                currentItem = arg0;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                // TODO Auto-generated method stub

            }
        });

//        textView1.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View arg0) {
//                // TODO Auto-generated method stub
//                viewPager.setCurrentItem(0);
//            }
//        });
//
//        textView2.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View arg0) {
//                // TODO Auto-generated method stub
//                viewPager.setCurrentItem(1);
//            }
//        });
//
//        textView3.setOnClickListener(new View.OnClickListener() {
//
//            @Override
//            public void onClick(View arg0) {
//                // TODO Auto-generated method stub
//                viewPager.setCurrentItem(2);
//            }
//        });

        //     请求好友数据
        UtMessage.MC_RequestFriends.Builder builder= UtMessage.MC_RequestFriends.newBuilder();
        ServerSession.getInstance().sendMessage(UtMessage.MessagePacket.MessageType.RequestFriends, builder.build().toByteString());
    }
//
//    private void getData() {
//        int[] imageIds = { R.drawable.world, R.drawable.friend_1,
//                R.drawable.friend_2, R.drawable.friend_3, R.drawable.friend_4, R.drawable.friend_5,
//                R.drawable.friend_6, R.drawable.friend_7, R.drawable.friend_8, R.drawable.friend_9,
//            };
//
//        String[] names = { "世界", "刘鑫", "曹玉灯", "于雨雨", "张政", "崔少平", "吴毅", "刘江海", "赵宇晴", "肖凯戈"};
//
//        for(int i=0;i<imageIds.length;i++){                  //将数据添加到集合中
//            friendList.add(new Friend(imageIds[i],names[i]));  //将图片id和对应的name存储到一起
//        }
//    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.main, menu);
//        return true;
//    }

    private void initFragment(int index) {
        // 由于是引用了V4包下的Fragment，所以这里的管理器要用getSupportFragmentManager获取
        FragmentManager fragmentManager = getSupportFragmentManager();
        // 开启事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 隐藏所有Fragment
        hideFragment(transaction);
        switch (index) {
            case 0:
//                if (homeFragment == null) {
//                    homeFragment = new HomeFragment();
//                    transaction.add(R.id.fl_content, homeFragment);
//                } else {
//                    transaction.show(homeFragment);
//                }
//                break;
//            case 1:
//                if (selfFragment == null) {
//                    selfFragment = new AddressFragment();
//                    transaction.add(R.id.fl_content, selfFragment);
//                } else {
//                    transaction.show(selfFragment);
//                }

                break;
            default:
                break;
        }
        // 提交事务
        transaction.commit();
    }

    //隐藏Fragment
    private void hideFragment(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (selfFragment != null) {
            transaction.hide(selfFragment);
        }
    }


    /**
     * 监听Back键按下事件,方法1:
     * 注意:
     * super.onBackPressed()会自动调用finish()方法,关闭
     * 当前Activity.
     * 若要屏蔽Back键盘,注释该行代码即可
     */
    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        ServerSession.getInstance().stopWebSocket();
        startActivity(new Intent(this, LogonActivity.class));
        finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    private void checkNewMessage(){

        for (Friend friend : friendList){
            ArrayList<String> chatList = ChatManager.getInstance().getChat(friend.getName());
            if (chatList != null && !chatList.isEmpty()) {

                friend.setNewMessage(true);
                ((FriendAdapter) lvFriends.getAdapter()).notifyDataSetChanged();
            }
        }
    }

    private void updateOnline(String name, boolean isOnline){

        if (name == null) return;

        boolean isInList = false;

        for (Friend friend : friendList){
            if (friend.getName().equals(name)){
//                if (friend.getOnline() == isOnline) break;
                friend.setOnline(isOnline);
                isInList = true;
                break;
            }
        }
        if (!isInList){
            friendList.add(new Friend(Friend.imageIds[Friend.imageIds.length - 1], name, true));
        }

        //重新排序
        Collections.sort(friendList, new SortFriendByOnline());

        ((FriendAdapter) lvFriends.getAdapter()).notifyDataSetChanged();
    }
    //判断界面是否在顶层
    private boolean isTopActivity()
    {
        boolean isTop = false;
        ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (cn.getClassName().contains(TAG))// TAG为Activity的全称
        {
            isTop = true;
        }
        return isTop;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_home:
                viewPager.setCurrentItem(0);
                break;
            case R.id.ll_self:
                viewPager.setCurrentItem(1);
            default:
                break;
        }
    }
}


